package org.grow.infru.controller;

import org.grow.infru.dao.DoubleBillRepository;
import org.grow.infru.dao.TestBillRepository;
import org.grow.infru.entity.DoubleBill;
import org.grow.infru.entity.DoubleDetail;
import org.grow.infru.entity.TestBill;
import org.grow.infru.service.CodeGene;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @Author: xwg
 * @CreateDate: 2022/1/21
 */
@RequestMapping("/doubleBill")
@RestController
public class DoubleBillController {

    @Autowired
    private ThreadLocal<CodeGene> codeGeneThreadLocal;
    @Autowired
    private DoubleBillRepository doubleBillRepository;
    @PostMapping("/insert")
    public DoubleBill insert(@RequestBody DoubleBill doubleBill){
        System.out.println("将要保存： "+doubleBill);
        DoubleDetail doubleDetail = doubleBill.getDoubleDetails().get(0);
        if (doubleDetail!=null){

            System.out.println("测试内存中的状态 子认父亲？ : " + (doubleDetail.getDoubleBill()!=null));
        }

//     子不认父的情况下 外键无法插入
        doubleBill.getDoubleDetails().forEach(x->{
            x.setDoubleBill(doubleBill);
        });
//        补做了双向关联后  插入优化成了两条insert语句


        doubleBill.setBillCode(codeGeneThreadLocal.get().nextCode("DB"));
        doubleBill.setVersion(0);
        doubleBill.setBillMadeTime(LocalDateTime.now());
        DoubleBill save = doubleBillRepository.save(doubleBill);
        System.out.println(save);
        return save;
    }

    @GetMapping("/find/{code}")
    public Optional<DoubleBill> findByPk(@PathVariable("code") String code) {
        Optional<DoubleBill> id = doubleBillRepository.findById(code);
//        System.out.println("=======test===eager");
//        fetch type lazy时候 查询语句不是连表 而responsebody注解序列化时候会补充
        return id;
    }

    @PostMapping("/modify")
    public DoubleBill modify(@RequestBody DoubleBill doubleBill) {
//        修改一个领域实体 = one的修改和many的增删改

//        依然需要完成双向关系 不然无法写入外键
//        双向关系的特点是 json解析出的对象还需要额外手动绑定一次关系
        doubleBill.getDoubleDetails().forEach(x->{
            x.setDoubleBill(doubleBill);
        });
        DoubleBill save = doubleBillRepository.save(doubleBill);
        return save;

    }
}
